package net.kuratkoo.jidelnicekvut;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class MyHttpClient {

    public static final String TAG = "JidelnicekVUT|MyHttpClient";
    HttpClient httpclient = new DefaultHttpClient();
    List<NameValuePair> nameValuePairs;
    HttpPost httppost;
    HttpResponse response;
    private String encoding = "UTF-8";

    public MyHttpClient(String url) {
        this.nameValuePairs = new ArrayList<NameValuePair>(2);
        this.httppost = new HttpPost(url);
    }

    public MyHttpClient(String url, String encoding) {
        this.nameValuePairs = new ArrayList<NameValuePair>(2);
        this.httppost = new HttpPost(url);
        this.encoding = encoding;
    }

    public void setPostData(String key, String value) {
        this.nameValuePairs.add(new BasicNameValuePair(key, value));
    }

    public void execute() throws MyHttpClientException  {
        try {
            this.httppost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs, "UTF-8"));
            this.response = this.httpclient.execute(this.httppost);
        } catch (UnsupportedEncodingException uee) {
            throw new MyHttpClientException(uee.getMessage(), uee.getCause());
        } catch (IOException ioe) {
            throw new MyHttpClientException(ioe.getMessage(), ioe.getCause());
        }
    }

    public String getResponse() throws MyHttpClientException  {
        StringBuilder out = new StringBuilder();
        try {
            char[] c = new char[20480];
            int n;

            InputStreamReader is = new InputStreamReader(this.response.getEntity().getContent(), this.encoding);


            while ((n = is.read(c)) != -1) {
                out.append(new String(c, 0, n));
            }
        } catch (UnsupportedEncodingException uee) {
            throw new MyHttpClientException(uee.getMessage(), uee.getCause());
        } catch (IOException ioe) {
            throw new MyHttpClientException(ioe.getMessage(), ioe.getCause());
        }
        return out.toString();
    }
}
